//
//  MNDTenderTransferingViewController.m
//  minidai
//
//  Created by 谭谭伟 on 17/5/14.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDTenderTransferingViewController.h"
#import "MNDTenderTransferModel.h"
#import "MNDTransferingTableViewCell.h"
#import "MNDTransferingDetailViewController.h"
#import "SYRefreshControl.h"
@interface MNDTenderTransferingViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (strong, nonatomic) NSMutableArray<MNDTenderTransferModel*> *tenderTransferModelArray;
@property (assign, nonatomic) NSInteger pageNum;
@property (weak, nonatomic) IBOutlet UITableView *transferingTableView;


@end

@implementation MNDTenderTransferingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
   
}

- (void)showContentLoadData {
    [self loadData:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self loadData:YES];

    
}
- (void)setupUI {
    self.transferingTableView.rowHeight = UITableViewAutomaticDimension;
    self.transferingTableView.estimatedRowHeight = 44;
    WeakSelf(self);
    [SYRefreshControl configGifMJRefresh:self.transferingTableView refreshType:MJRefreshSupportALl beginRefresh:NO timeLabelHidden:YES stateLabelHidden:YES refreshBlock:^{
        [weakself loadData:YES];
    }loadMoreBlock:^{
      [weakself loadData:NO];
  }];
}

#pragma mark -懒加载

- (NSMutableArray<MNDTenderTransferModel *> *)tenderTransferModelArray {
    if (!_tenderTransferModelArray) {
        _tenderTransferModelArray = [[NSMutableArray alloc]init];
    }
    return _tenderTransferModelArray;
}

#pragma mark -加载数据
- (void)loadData:(BOOL)isPullDown {
    if (self.tenderTransferModelArray.count <= 0) {
        [self.view beginLoading];
    }
    if (isPullDown) {
        if (self.tenderTransferModelArray.count <= 0) {
            [self.view beginLoading];
        }
        _pageNum = 1;
    }else {
        _pageNum++;
    }
    __weak typeof(self) weakSelf = self;
    
    //转让中数据获取
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"perpage": @(_pageNum), @"pagesize": @5, @"creditor_status": @1}];
    
    [APIManager sendRequestWithPath:API_TENDER_TRANSFER_LIST parameters:params method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            NSArray *modelArray = [MNDTenderTransferModel mj_objectArrayWithKeyValuesArray:responseModel.data[@"li"]];
            [SYRefreshControl configAfterLoading:weakSelf.transferingTableView hasData:modelArray.count];
            if (isPullDown) {
                [weakSelf.view configBlankPage:SYBlankPageTypeNoData hasData:modelArray.count reloadButtonBlock:nil];
                [weakSelf.tenderTransferModelArray removeAllObjects];
            }
            [weakSelf.tenderTransferModelArray addObjectsFromArray:modelArray];
        } else {
            [SYRefreshControl configAfterLoading:weakSelf.transferingTableView hasData:YES];
            
            if (isPullDown) {
                [weakSelf.view configBlankPage:SYBlankPageTypeError hasData:weakSelf.tenderTransferModelArray.count reloadButtonBlock:^(id sender) {
                    [weakSelf loadData:YES];
                }];
            } else {
                [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
            }
        }
        [weakSelf.transferingTableView reloadData];
        
    } onFailure:^(NSError *error) {
        [SYRefreshControl configAfterLoading:weakSelf.transferingTableView hasData:YES];
        if (isPullDown) {
            SYBlankPageType blankType = [weakSelf.view blankPageTypeWithError:error];
            [weakSelf.view configBlankPage:blankType hasData:weakSelf.tenderTransferModelArray.count reloadButtonBlock:^(id sender) {
                [weakSelf loadData:isPullDown];
            }];
            
        } else {
            [NetworkProgressHUD showHudNetworkError:error];
        }
    }];
}

#pragma mark -UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    return 10;
    return self.tenderTransferModelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        MNDTenderTransferModel *transferingModel = self.tenderTransferModelArray[indexPath.row];
        MNDTransferingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MNDTransferingTableViewCell"];
        cell.brrowTitleLabel.text = transferingModel.borrow_title;
        cell.borrowYearAprLabel.text = [NSString stringWithFormat:@"%@%%",transferingModel.borrow_year_apr];
        cell.creditorPrincipalLabel.text = transferingModel.creditor_principal;
        cell.creditorPriceLabel.text = transferingModel.creditor_price;
        cell.creditorPublishDateLabel.text = [NSString stringWithFormat:@"转让日期：%@",transferingModel.creditor_publish_date];
        cell.creditorDeadlineLabel.text = [NSString stringWithFormat:@"%@个月",transferingModel.creditor_deadline];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"TenderTransfer" bundle:nil];
    MNDTransferingDetailViewController *transferDetailVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDTransferingDetailViewController"];
    transferDetailVC.creditorId = self.tenderTransferModelArray[indexPath.row].creditor_id;
    transferDetailVC.transferStatus = @"0";
    transferDetailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:transferDetailVC animated:YES];

}

//撤销转让侧滑
//侧滑
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    WeakSelf(self);
    //债权转让侧滑
    UITableViewRowAction *transferRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault  title:@"撤销转让" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:@"您确定要撤销转让该项目吗？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *comfirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [NetworkProgressHUD showHud];
            //取消转让接口调用
            NSDictionary *params = [MNDSign signedParamWithDict:@{@"creditor_id": weakself.tenderTransferModelArray[indexPath.row].creditor_id}];
            
            [APIManager sendRequestWithPath:API_TENDER_TRANSFER_CANCEL parameters:params method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
                if (responseModel.status == ResponseSuccess) {
                    [NetworkProgressHUD showHudMsg:responseModel.msg[@"success"]];
                    [weakself loadData:YES];
                } else {
                    [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
                }
            } onFailure:^(NSError *error) {
                [NetworkProgressHUD showHudNetworkError:error];
            }];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertVC addAction:comfirmAction];
        [alertVC addAction:cancelAction];
        
        [self presentViewController:alertVC animated:YES completion:nil];
        
    }];
    transferRowAction.backgroundColor = GlobalColor;
    return @[transferRowAction];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
